﻿
namespace Helpers
{
	using System.IO;
	using System.Runtime.Serialization.Formatters.Binary;

	public static class Extensions
	{
		public static byte[] ToObjectFromByteArray<T>(this T obj) where T : class 
		{
			if (obj == null)
				return null;

			BinaryFormatter bf = new BinaryFormatter();
			using ( MemoryStream ms = new MemoryStream () )
			{
				bf.Serialize(ms, obj);
				return ms.ToArray();
			}
		}

		// Convert a byte array to an Object
		public static T ToObjectFromoByteArray<T>(this byte[] arrBytes) where T : class 
		{
			T obj;
			BinaryFormatter binForm = new BinaryFormatter();

			using ( MemoryStream memStream = new MemoryStream () )
			{				
				memStream.Write(arrBytes, 0, arrBytes.Length);
				memStream.Seek(0, SeekOrigin.Begin);
				obj = ( T ) binForm.Deserialize ( memStream );
			}
			return obj;
		}
	}
}
